# app/models/user.py
from app import db
from datetime import datetime
from sqlalchemy import Enum


class User(db.Model):
    __tablename__ = 'users'

    user_id = db.Column(db.String(36), primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(100), unique=True)
    password_hash = db.Column(db.String(128))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    status = db.Column(Enum('online', 'idle', 'dnd', 'offline', name='user_status'), default='offline')
    avatar_url = db.Column(db.String(255))
    actServer = db.Column(db.String(36))
    is_registered = db.Column(db.Boolean, default=False)
    join_default = db.Column(db.Boolean, default=True)
    bio = db.Column(db.TEXT)
    tags = db.Column(db.JSON)

    owned_servers = db.relationship('Server', back_populates='owner', foreign_keys='Server.owner_id')
    memberships = db.relationship('ServerMember', back_populates='user')
    privacy_settings = db.relationship('PrivacySetting', back_populates='user', uselist=False)
    friend_groups = db.relationship('FriendGroup', back_populates='user')
    initiated_friendships = db.relationship('Friend', foreign_keys='Friend.user_id', back_populates='initiator')
    received_friendships = db.relationship('Friend', foreign_keys='Friend.friend_id', back_populates='friend')
    direct_chats_user1 = db.relationship('DirectChat', foreign_keys='DirectChat.user1_id', back_populates='user1')
    direct_chats_user2 = db.relationship('DirectChat', foreign_keys='DirectChat.user2_id', back_populates='user2')
    messages_sent = db.relationship('Message', back_populates='sender', foreign_keys='Message.sender_id')
    files_uploaded = db.relationship('File', back_populates='uploader')
    playlists = db.relationship('Playlist', back_populates='owner')

    @property
    def channel_permissions(self):
        """获取用户在所有服务器中的频道权限"""
        permissions = []
        for membership in self.server_memberships:
            permissions.extend(membership.channel_permissions)
        return permissions

    def is_guest(self):
        return not self.is_registered

    def can_receive_dm(self, sender):
        """检查是否允许接收来自特定用户的私信"""
        if sender.id == self.id:
            return False

        if self.privacy_settings.allow_dm_from_all:
            return True

        if self.privacy_settings.allow_server_dm:
            # 检查是否在同服务器(逻辑需在业务层实现)
            pass

        # 检查好友关系
        return any(f.friend_id == sender.id and f.status == 'accepted'
                   for f in self.received_friendships)

    def __repr__(self):
        return f'<User {self.username}>'